const request = require("request");
const jsonfile = require("jsonfile");
const axios = require("axios");
const certs = require("./cert").cert;
const config = require("./config").config;

/*let putData = (fullData,times)=>{
    if(times === fullData.length){
        console.log("all data is put finish >> success");
        return false;
    }
    let postData = JSON.stringify({
        certificateNum:fullData[times].certificateNum,
        name:fullData[times].name,
        trainTime:fullData[times].trainTime,
        authenTime:fullData[times].authenTime,
        term:fullData[times].term,
        phone:fullData[times].phone,
        mailbox:fullData[times].mailbox,
        institution:fullData[times].institution,
        position:fullData[times].position,
    });
    request.post({
        url: `${config.host}/CreateNewTransaction`,
        form:{
	    key:uuid(),
	    value:new Buffer(postData).toString('base64')
        }
    }, function(error, response, body) {
        let data = JSON.parse(body);
        if(data.State === 200){
            let file = './cert.json';
            let json = {
                term:fullData[times].term,
                name:fullData[times].name,
                txId:data.Data
            };
            jsonfile.writeFile(file,json,{flag: 'a'},()=>{});
            putData(certs,times+1);
            console.log(data.Data);
        }else{
            console.error(`error ======== > ${data.Message}::::${JSON.stringify(data.Data)}`);
        }
    });
};*/
function uuid(len, radix) {
    let CHARS = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('');
    let chars = CHARS, uuid = [], i;
    radix = radix || chars.length;
    if (len) {
	for (i = 0; i < len; i++) uuid[i] = chars[0 | Math.random()*radix];
    } else {
	let r;
	uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-';
	uuid[14] = '4';
	for (i = 0; i < 36; i++) {
	    if (!uuid[i]) {
		r = 0 | Math.random()*16;
		uuid[i] = chars[(i === 19) ? (r & 0x3) | 0x8 : r];
	    }
	}
    }
    return uuid.join('');
}
// putData(certs,0);

let putData = (fullData,times)=>{
    if(times === fullData.length){
	console.log("all data is put finish >> success");
	return false;
    }
    let postData = JSON.stringify({
	certificateNum:fullData[times].certificateNum,
	name:fullData[times].name,
	trainTime:fullData[times].trainTime,
	authenTime:fullData[times].authenTime,
	term:fullData[times].term,
	phone:fullData[times].phone,
	mailbox:fullData[times].mailbox,
	institution:fullData[times].institution,
	position:fullData[times].position,
    });

    axios({
	method: 'post',
	url:`${config.host}/createnewtransaction`,
	headers: {
	    'content-type': 'application/json',
	},
	data: {
	    Name:"certChain",
	    Version:"1.0",
	    Method:"Init",
	    Args:["cert",postData]
	}
    }).then((data)=>{
	if(typeof data.data !== "undefined" && data.data !== null){
	    let file = './cert.json';
	    let json = {
		term:fullData[times].term,
		name:fullData[times].name,
		txId:data.data.Data.Figure
	    };
	    jsonfile.writeFile(file,json,{flag: 'a'},()=>{});
	    putData(certs,times+1);
	    console.log(json.txId);
	}
    });
    /*return false;
    request.post({
	url: `${config.host}/CreateNewTransaction`,
	form:{
	    key:uuid(),
	    value:new Buffer(postData).toString('base64')
	}
    }, function(error, response, body) {
	let data = JSON.parse(body);
	if(data.State === 200){
	    let file = './cert.json';
	    let json = {
		term:fullData[times].term,
		name:fullData[times].name,
		txId:data.Data
	    };
	    jsonfile.writeFile(file,json,{flag: 'a'},()=>{});
	    putData(certs,times+1);
	    console.log(data.Data);
	}else{
	    console.error(`error ======== > ${data.Message}::::${JSON.stringify(data.Data)}`);
	}
    });*/
};

let installChainCode = ()=>{
    return new Promise((suc,err)=>{
	axios({
	    method: 'post',
	    url:`${config.host}/contract/install`,
	    headers: {
		'content-type': 'application/json',
	    },
	    data: {
		Name:"certChain",
		Version:"1.0",
		File:"cGFja2FnZSBtYWluCgppbXBvcnQgKAoJImZtdCIKCSJzdHJjb252IgoJInRpbWUiCgoJc2hpbSAiZ2l0aHViLmNvbS90amZvYy90amZvYy9jb3JlL2NoYWluY29kZS9zaGltIgoJcGIgImdpdGh1Yi5jb20vdGpmb2MvdGpmb2MvY29yZS9jb21tb24vcHJvdG9jb2wvcGVlciIKKQoKLy/oh6rlt7Hlrp7njrDnmoTkuIDkuKogY2hhaW5jb2RlCnR5cGUgTXlDaGFpbmNvZGUgc3RydWN0IHsKfQoKZnVuYyAoY2MgTXlDaGFpbmNvZGUpIEluaXQoc3R1YiBzaGltLkN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UHJpbnRsbigiaW4gbXljaGFpbmNvZGUgSW52b2tlLiIpCglyZXR1cm4gc2hpbS5TdWNjZXNzKG5pbCkKfQoKZnVuYyBtYWluKCkgewoJZXJyIDo9IHNoaW0uU3RhcnQobmV3KE15Q2hhaW5jb2RlKSkKCWlmIGVyciAhPSBuaWwgewoJCWZtdC5QcmludGYoIkVycm9yIHN0YXJ0aW5nIG15IGNoYWluY29kZSA6ICVzIiwgZXJyKQoJfQp9Cg=="
	    }
	}).then((data)=>{
	    if(typeof data.data === "undefined" || data.data === null){
		suc({
		    code:400,
		    data:"",
		    msg:"服务错误",
		})
	    }else{
		suc({
		    code:data.data.State,
		    data:data.data.Data,
		    msg:data.data.Message,
		})
	    }
	});
    })
};
installChainCode().then((data)=>{
    if(data.code === 200){
	putData(certs,0);
    }else{
        console.log(JSON.stringify(data));
    }
});
// putData(certs,0);